package com.lw.leetcode.dp.c;

/**
 * Created with IntelliJ IDEA.
 * 115. 不同的子序列
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/17 11:03
 */
public class NumDistinct {


    public static void main(String[] args) {
        NumDistinct test = new NumDistinct();
        String str = "babgbag";
        String t = "bag";
        int i = test.numDistinct(str, t);
        System.out.println(i);
    }

    public int numDistinct(String s, String t) {
        int a = s.length();
        int b = t.length();
        if (a == 0 || b == 0) {
            return 0;
        }
        char[] as = s.toCharArray();
        char[] bs = t.toCharArray();
        int[] arr = new int[a];
        int sum = 1;
        for (int i = b - 1; i >= 0; i--) {
            char c = bs[i];
            for (int j = a - 1; j >= 0; j--) {
                int n = arr[j];
                arr[j] = c == as[j] ? sum : 0;
                sum += n;
            }
            sum = 0;
        }
        for (int i : arr) {
            sum += i;
        }
        return sum;
    }

    public int numDistinct2(String s, String t) {
        int a = s.length();
        int b = t.length();
        if (a == 0 || b == 0) {
            return 0;
        }
        char[] as = s.toCharArray();
        char[] bs = t.toCharArray();
        int[][] arr = new int[b + 1][a];
        int sum = 1;
        for (int i = b - 1; i >= 0; i--) {
            char c = bs[i];
            int[] item = arr[i];
            int[] last = arr[i + 1];
            for (int j = a - 1; j >= 0; j--) {
                if (c == as[j]) {
                    item[j] = sum;
                }
                sum += last[j];
            }
            sum = 0;
        }
        int[] item = arr[0];
        for (int i : item) {
            sum += i;
        }
        return sum;
    }
}
